<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <el-input
          v-model="query.value"
          clearable
          placeholder="输入搜索内容"
          style="width: 200px;"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        />
        <el-select
          v-model="query.type"
          clearable
          placeholder="类型"
          class="filter-item"
          style="width: 130px"
        >
          <el-option
            v-for="item in queryTypeOptions"
            :key="item.key"
            :label="item.display_name"
            :value="item.key"
          />
        </el-select>
        <rrOperation :crud="crud" />
      </div>
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission" />
      <el-button type="info" class="el-icon-sort importantBtn" @click="handleImportantBtn">导入</el-button>
      <!--表单组件-->
      <el-dialog
        :close-on-click-modal="false"
        :before-close="crud.cancelCU"
        :visible.sync="crud.status.cu > 0"
        :title="crud.status.title"
        width="530px"
      >
        <el-form ref="form" :model="form" :rules="rules" size="small" label-width="100px">
          <el-form-item label="考勤点名称" prop="siteSettingId">
            <el-select v-model="form.siteSettingId" filterable placeholder="请选择" style="width:95%">
              <el-option
                v-for="item in ateTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="LED信息" prop="witLedInfoSmallList" style="margin-top:20px;">
            <el-select
              v-model="form.witLedInfoSmallList"
              style="width:95%"
              multiple
              placeholder="请选择"
              @remove-tag="deleteLedLists"
              @change="changeLedLists"
            >
              <el-option
                v-for="(item,index) in witLedInfoSmallList"
                :key="index"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="视频信息" prop="witVideoInfoSmallList" style="margin-top:20px;">
            <el-select
              v-model="form.witVideoInfoSmallList"
              style="width:95%"
              multiple
              placeholder="请选择"
              @remove-tag="deleteVideoLists"
              @change="changeVideoLists"
            >
              <el-option
                v-for="(item,index) in witVideoInfoSmallList"
                :key="index"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <!--          <el-form-item label="考勤设备状态" prop="state">-->
          <!--            <el-select v-model="form.state" filterable style="width:95%">-->
          <!--              <el-option-->
          <!--                v-for="(item,index) in dict.attendance_equipment_status"-->
          <!--                :key="index"-->
          <!--                :label="item.label"-->
          <!--                :value="item.value"-->
          <!--              />-->
          <!--            </el-select>-->
          <!--          </el-form-item>-->
          <el-form-item label="设备名称" prop="name">
            <el-input v-model="form.name" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="设备编号" prop="equipmentNumber">
            <el-input v-model="form.equipmentNumber" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="form.remark" style="width: 370px;" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
        </div>
      </el-dialog>
      <!--表单组件-->
      <el-dialog
        :close-on-click-modal="false"
        :visible.sync="handleFormDialog"
        title="新增门禁信息"
        width="530px"
      >
        <el-form ref="form" :model="profile" :rules="rules" size="small" label-width="100px">
          <el-form-item label="设备编号" prop="sn">
            <el-input v-model.number="profile.sn" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="iP地址" prop="ip">
            <el-input v-model="profile.ip" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="端口号" prop="port">
            <el-input v-model="profile.port" style="width: 370px;" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="handleFormDialog=false">取消</el-button>
          <el-button type="primary" @click="submitImportClickBtn">确认</el-button>
        </div>
      </el-dialog>
      <!--表格渲染-->
      <el-table
        ref="table"
        v-loading="crud.loading"
        :data="crud.data"
        size="small"
        style="width: 100%;margin-top: -25px;"
        @selection-change="crud.selectionChangeHandler"
      >
        <el-table-column type="selection" align="center" max-width="120" />
        <el-table-column
          v-if="columns.visible('siteSettingId')"
          prop="siteSettingName"
          label="考勤点名称"
        />
        <el-table-column v-if="columns.visible('name')" prop="name" label="设备名称" />
        <el-table-column
          v-if="columns.visible('equipmentNumber')"
          prop="equipmentNumber"
          label="设备编号"
        />
        <el-table-column v-if="columns.visible('ip')" prop="ip" label="IP地址" />
        <el-table-column v-if="columns.visible('mask')" prop="mask" label="掩码" />
        <el-table-column v-if="columns.visible('gateway')" prop="gateway" label="网关" />
        <el-table-column
          v-if="columns.visible('macAddress')"
          prop="macAddress"
          label="MAC地址"
          min-width="120%"
        />
        <el-table-column v-if="columns.visible('status')" prop="status" label="状态">
          <template
            slot-scope="scope"
          >{{ dict.label.attendance_equipment_status[scope.row.status] }}</template>
        </el-table-column>
        <el-table-column v-if="columns.visible('remark')" prop="remark" label="备注" />
        <el-table-column
          v-permission="['admin','attendanceEquipment:edit','attendanceEquipment:del']"
          label="操作"
          width="150px"
          align="center"
        >
          <template slot-scope="scope">
            <udOperation :data="scope.row" :permission="permission" />
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
    </div>
  </div>
</template>

<script>
import crudAttendanceEquipment from '@/api/sapientialSite/attendanceEquipment'
import { ledQueryListForSimple } from '@/api/sapientialSite/attendanceEquipment'
import { videoQueryListForSimple } from '@/api/sapientialSite/attendanceEquipment'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import { getAllSiteSetting } from '@/api/sapientialSite/attendanceSiteSetting'
import { addLead } from '@/api/sapientialSite/attendanceEquipment'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'

let witLedInfo = []
let witVideoInfo = []

// crud交由presenter持有
const defaultCrud = CRUD({
  title: '考勤设备',
  url: 'api/attendanceEquipment',
  sort: 'id,desc',
  crudMethod: { ...crudAttendanceEquipment }
})
const defaultForm = {
  id: null,
  siteSettingId: null,
  name: null,
  equipmentNumber: null,
  remark: null,
  isDelete: null,
  createUser: null,
  createDate: null,
  updateUser: null,
  updateDate: null,
  witLedInfoSmallList: [],
  witVideoInfoSmallList: []
}
export default {
  name: 'AttendanceEquipment',
  components: { pagination, crudOperation, rrOperation, udOperation },
  mixins: [presenter(defaultCrud), header(), form(defaultForm), crud()],
  dicts: ['attendance_equipment_status'],
  data() {
    return {
      permission: {
        add: ['admin', 'attendanceEquipment:add'],
        edit: ['admin', 'attendanceEquipment:edit'],
        del: ['admin', 'attendanceEquipment:del']
      },
      rules: {
        siteSettingId: [
          { required: true, message: '请选择考勤点名称', trigger: 'blur' }
        ],
        name: [{ required: true, message: '请输入设备名称', trigger: 'blur' }],
        equipmentNumber: [
          { required: true, message: '请输入设备编号', trigger: 'blur' }
        ],
        witLedInfoSmallList: [
          { required: true, message: '请选择LED信息', trigger: 'blur' }
        ],
        witVideoInfoSmallList: [
          { required: true, message: '请选择视频信息', trigger: 'blur' }
        ],
        ip: [{ required: true, message: '请输入ip地址', trigger: 'blur' }],
        port: [{ required: true, message: '请输入端口号', trigger: 'blur' }],
        sn: [
          {
            required: true,
            message: '请输入设备编号',
            trigger: 'blur',
            type: 'number'
          }
        ]
      },
      queryTypeOptions: [
        { key: 'siteSettingName', display_name: '考勤点名称' },
        { key: 'name', display_name: '设备名称' },
        { key: 'equipmentNumber', display_name: '设备编号' }
      ],
      ateTypeOptions: [],
      witLedInfoSmallList: [],
      witVideoInfoSmallList: [],
      handleFormDialog: false,
      profile: {
        ip: '',
        port: '',
        sn: ''
      }
    }
  },
  created() {
    this.crud.optShow.add = false
  },
  methods: {
    changeLedLists(value) {
      witLedInfo = []
      value.forEach(function(data, index) {
        const led = { id: data }
        witLedInfo.push(led)
      })
      console.log('led信息对象数组', witLedInfo)
    },
    changeVideoLists(value) {
      witVideoInfo = []
      value.forEach(function(data, index) {
        console.log('data数据', data)
        const video = { id: data }
        witVideoInfo.push(video)
      })
      console.log('video视频对象数组', witVideoInfo)
    },
    // 获取数据前设置好接口地址
    [CRUD.HOOK.beforeRefresh]() {
      const query = this.query
      console.log(query)
      this.crud.params = {}
      if (query.type && query.value) {
        this.crud.params[query.type] = query.value
      }
      return true
    },
    [CRUD.HOOK.afterEditError](crud) {
      this.afterErrorMethod(crud)
    },
    afterErrorMethod(crud) {
      // 恢复select
      const initLedList = []
      const initVideoList = []
      witLedInfo.forEach(function(led, index) {
        initLedList.push(led.id)
      })
      console.log('恢复selectled信息', initLedList)
      witVideoInfo.forEach(function(video, index) {
        initVideoList.push(video.id)
      })
      console.log('恢复select视频播放', initVideoList)
    },
    // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form) {
      this.getAttendanceNameOptions()
      this.getLedQueryListOptions()
      this.getVideoQueryListOptions()
    },
    deleteLedLists(value) {
      witLedInfo.forEach(function(data, index) {
        if (data.id === value) {
          witLedInfo.splice(index, value)
        }
      })
    },
    deleteVideoLists(value) {
      witVideoInfo.forEach(function(data, index) {
        if (data.id === value) {
          witVideoInfo.splice(index, value)
        }
      })
    },
    // 打开编辑弹窗前做的操作
    [CRUD.HOOK.beforeToEdit](crud, form) {
      witLedInfo = []
      witVideoInfo = []
      const witLedInfoSmallList = []
      const witVideoInfoSmallList = []
      if (form.witLedInfoSmallList) {
        form.witLedInfoSmallList.forEach(function(led, index) {
          console.log('led信息', led)
          witLedInfoSmallList.push(led.id)
          // 初始化编辑时候的角色
          const rol = { id: led.id }
          witLedInfo.push(rol)
        })
        console.log('编辑led信息', witLedInfo)
      }

      if (form.witVideoInfoSmallList) {
        form.witVideoInfoSmallList.forEach(function(video, index) {
          witVideoInfoSmallList.push(video.id)
          // 初始化编辑时候的考勤点名称
          const waj = { id: video.id }
          witVideoInfo.push(waj)
        })
        console.log('编辑video信息', witVideoInfo)
      }
      form.witLedInfoSmallList = witLedInfoSmallList
      form.witVideoInfoSmallList = witVideoInfoSmallList
    },
    // 提交前做的操作
    [CRUD.HOOK.afterValidateCU](crud) {
      if (this.witLedInfoSmallList.length === 0) {
        this.$message({
          message: 'led信息不能为空',
          type: 'warning'
        })
        return false
      } else if (this.witVideoInfoSmallList.length === 0) {
        this.$message({
          message: '视频信息不能为空',
          type: 'warning'
        })
        return false
      } else if (this.ateTypeOptions.length === 0) {
        this.$message({
          message: '考勤点名称不能为空',
          type: 'warning'
        })
        return false
      }
      crud.form.witLedInfoSmallList = witLedInfo
      crud.form.witVideoInfoSmallList = witVideoInfo
      return true
    },
    getAttendanceNameOptions() {
      getAllSiteSetting()
        .then(res => {
          this.ateTypeOptions = res
        })
        .catch(() => {})
    },
    // 获取LED数据
    getLedQueryListOptions() {
      ledQueryListForSimple()
        .then(res => {
          this.witLedInfoSmallList = res
        })
        .catch(() => {})
    },
    // 获取视频信息
    getVideoQueryListOptions() {
      videoQueryListForSimple()
        .then(res => {
          this.witVideoInfoSmallList = res
        })
        .catch(() => {})
    },
    handleImportantBtn() {
      this.handleFormDialog = true
    },
    // 添加
    submitImportClickBtn() {
      var params = {
        sn: this.profile.sn,
        port: this.profile.port,
        ip: this.profile.ip
      }
      console.log(JSON.stringify(params))
      addLead(JSON.stringify(params))
        .then(res => {
          this.crud.toQuery()
          this.profile.sn = ''
          this.profile.port = ''
          this.profile.ip = ''
          this.handleFormDialog = false
        })
        .catch(() => {})
    }
  }
}
</script>

<style scoped>
@media screen and (min-width: 980px) {
  .importantBtn {
    position: relative;
    left: 170px;
    top: -45px;
    height: 29px;
    line-height: 8px;
    display: inline-block;
    vertical-align: middle;
  }
}
</style>
